<?php

namespace app\api\controller\xiluhouse;

use app\common\controller\Api;

/**
 * @title   通用类
 * @desc    获取一些通用的接口
 */
class Universal extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = '*';
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = '*';

    /**
     * @title  广告图
     * @desc  获取广告
     *
     * @param int $position  1  广告位置:1=首页悬浮,2=首页顶部轮播,3=首页中间轮播,4=个人中心轮播,5=资讯页轮播
     * @param int $position_type  1  返回数据类型:1=单个地方数据（就返回一个数组）,2=首页3个地方的广告（返回3个数组）
     *
     * @return int $goto_type  - 跳转方式:1=不跳转,2=跳转外链,3=跳转内链,4=我要订阅,5=活动外链
     * @return int $goto_param  - 内链参数（例如这里返回了参数值为1，且是跳转房源详情，就是查询id=1的房源）
     * @return int $inside_pages_id  - 内链跳转id（该id作为原生跳转页面的标识）
     * @return int $goto_url  - 外链链接
     * @return int $share_title  - 分享标题
     * @return int $share_desc  - 分享描述
     */
    public function advert_data()
    {
        $model= new \app\common\model\xiluhouse\Advert;
        $map['position']=$this->request->param('position/d',1);
        $position_type=$this->request->param('position_type/d',1);
        $with=['insidepages'];
        $map['advert.status']='normal';
        $data = [];
        if($position_type==1){
            $data=$model->with($with)->where($map)->order(['weigh'=>'desc','id'=>'desc'])->select();
        }else if($position_type==2){
            $data['data1']=$model->with($with)->where(['position'=>1,'advert.status'=>'normal'])->order(['weigh'=>'desc','id'=>'desc'])->select();
            $data['data2']=$model->with($with)->where(['position'=>2,'advert.status'=>'normal'])->order(['weigh'=>'desc','id'=>'desc'])->select();
            $data['data3']=$model->with($with)->where(['position'=>3,'advert.status'=>'normal'])->order(['weigh'=>'desc','id'=>'desc'])->select();
        }
        $this->success('', $data);
    }

    /**
     * @title  城市
     * @desc  获取所有城市（按字母顺序排序）
     *
     */
    public function city_data(){
        $model= new \app\common\model\xiluhouse\Area;
        $data=$model->getCityList();
        $this->success('', $data);
    }

    /**
     * @title  城市下区县
     * @desc  获取某个城市的所有区县
     *
     * @param string $city  上海市  城市名称
     *
     */
    public function region_data(){
        $model= new \app\common\model\xiluhouse\Area;
        $city=$this->request->param('city/s','上海市');
        $data=$model->getRegionStreet($city,2);
        $this->success('', $data);
    }

    /**
     * @title  城市下区县、街道
     * @desc  获取某个城市的所有区县、街道
     *
     * @param string $city  上海市  城市名称
     *
     */
    public function region_street_data(){
        $model= new \app\common\model\xiluhouse\Area;
        $city=$this->request->param('city/s','上海市');
        $data=$model->getRegionStreet($city);
        $this->success('', $data);
    }

    /**
     * @title  街道 -lixixi
     * @param string $region
     *
     */
    public function street_data(){
        $model= new \app\common\model\xiluhouse\Area;
        $region=$this->request->param('region/s','上海市');

        $region_id = $model->where('level', 3)->where('name', 'like', $region . '%')->value('id') ?: 0;
        if (!$region_id) {
            $this->success('', []);
        }
        $data=$model ->field("id,name,pid")->where('level', 4)->where('pid', $region_id)->select();
        $this->success('', $data);
    }

    /**
     * @title  热门搜索数据
     * @desc  获取某个城市的热门搜索数据
     *
     * @param string $city  上海市  城市名称
     *
     */
    public function hot_search_data(){
        $model= new \app\common\model\xiluhouse\HouseHostSearch;
        $city=$this->request->param('city/s','上海市');
        $data=$model
            ->where('status','normal')
            ->where('city','like',$city.'%')
            ->select();
        $this->success('', $data);
    }

    /**
     * @title  根据经纬度获取城市名称
     *
     * @param string  $lng    无  经度
     * @param string  $lat    无  纬度
     * 
     * @return string $city  无  城市名称
     */
    public function get_city_from_lng_lat(){
        $lng=$this->request->param('lng/s','');
        $lat=$this->request->param('lat/s','');
        if(!$lng||!$lat){
            $this->error('参数错误');
        }
        // 使用了腾讯地图 不需要转
        // 如果APP使用了百度地图需要转一下
        $model= new \app\common\model\xiluhouse\Area;
        $res=$model->getCityFromLngLat($lng,$lat);
        if(!$res){
            $this->error('该定位城市暂时没有开通楼盘信息！');
        }
        $this->success('', $res);
    }

    /**
     * @title  根据城市获取当前地铁数据
     * @param string $city   上海市  所在城市
     */
    public function subways_data(){
        // 搜索地铁
        $city = $this->request->param('city','上海市');
        $subwaymodel=new \app\common\model\xiluhouse\Subway;
        $subwaysList=$subwaymodel->where('name_city','like',$city.'%')->select();
        foreach ($subwaysList as $key => $value) {
            $subwaysList[$key]['list']=\app\common\model\xiluhouse\SubwayPlatform::where('find_in_set("'.trim($value['code']).'",subways)')->select();
        }
        $this->success('',$subwaysList);
    }

    /**
     * @title  楼盘搜索数据
     * @desc  搜索楼盘的价格、户型、类型、品牌开发商、tag标签
     */
    public function search_field_data(){
        //获取搜索价格
        $data['priceData']=\app\common\model\xiluhouse\HouseSearchPrice::where('status','normal')->where('classify',1)->orderRaw('weigh desc,id desc')->select();

        //获取搜索户型
        $data['roomnumData']=\app\common\model\xiluhouse\HouseSearchRoomnum::where('status','normal')->orderRaw('weigh desc,id desc')->select();

        //类型
        $data['typeData']=\app\common\model\xiluhouse\HouseType::where('status','normal')->orderRaw('weigh desc,id desc')->select();
        //品牌开发商
        $data['developerData']=\app\common\model\xiluhouse\HouseDeveloper::where('status','normal')->orderRaw('weigh desc,id desc')->select();

        //tag标签
        $data['tagData']=\app\common\model\xiluhouse\HouseTag::where('status','normal')->where('classify',1)->orderRaw('weigh desc,id desc')->select();

        $this->success('',$data);
    }

    /**
     * @title  租房搜索数据
     * @desc  搜索租房的价格、户型、类型、tag标签
     */
    public function search_field_data2(){
        //获取搜索价格
        $data['priceData']=\app\common\model\xiluhouse\HouseSearchPrice::where('status','normal')->where('classify',2)->orderRaw('weigh desc,id desc')->select();

        //获取搜索户型
        $data['roomnumData']=\app\common\model\xiluhouse\HouseSearchRoomnum::where('status','normal')->orderRaw('weigh desc,id desc')->select();

        //获取搜索户型
        $data['rentalMode'] = \app\common\model\xiluhouse\RentalMode::where('status','normal')->orderRaw('weigh desc,id desc')->select();

        //类型
        $data['typeData']=\app\common\model\xiluhouse\HouseType::where('status','normal')->orderRaw('weigh desc,id desc')->select();

        //tag标签
        $data['tagData']=\app\common\model\xiluhouse\HouseTag::where('status','normal')->where('classify',2)->orderRaw('weigh desc,id desc')->select();

        $this->success('',$data);
    }

    /**
     * @title  户型搜索数据
     */
    public function search_roomnum_data(){
        //获取搜索户型
        $roomnumData=\app\common\model\xiluhouse\HouseSearchRoomnum::where('status','normal')->orderRaw('weigh desc,id desc')->select();
        $this->success('',$roomnumData);
    }
    
    /**
     * @title   首页数据
     * @desc  获取首页展示标签、首页当前城市房价均价、上下轮播文章、推荐咨询师
     * @param string $city   上海市  所在城市
     */
    public function mini_index_data(){
        $city=$this->request->param('city/s','上海市');
        // 首页展示标签
        $data['indexShowData']=\app\common\model\xiluhouse\HouseIndexShow::where('status','normal')->orderRaw('weigh desc,id desc')->select();

        // 城市房价
//        $cityHousePriceData1=\app\common\model\xiluhouse\HouseHistoryPrice::where('status','normal')->where('city','like',$city.'%')->where('year_month',date('Y-m',strtotime('first day of -1 month')))->find();
        $cityHousePriceData1=\app\common\model\xiluhouse\HouseHistoryPrice::where('status','normal')->where('city','like',$city.'%')->where('year_month',date('Y-m'))->find();
        $cityHousePriceData2=\app\common\model\xiluhouse\HouseHistoryPrice::where('status','normal')->where('city','like',$city.'%')->where('year_month',date('Y-m',strtotime('first day of -1 month')))->find();

        $data['cityHousePriceData']['now_average_price']=$cityHousePriceData1?$cityHousePriceData1['average_price']:'';
        $data['cityHousePriceData']['now_trade_num']=$cityHousePriceData1?$cityHousePriceData1['trade_num']:'';
        //用本月数据减去上月数据
        $data['cityHousePriceData']['average_price_sub']=$cityHousePriceData1?$cityHousePriceData1['average_price']-($cityHousePriceData2?$cityHousePriceData2['average_price']:0):0;
        // 比上月的百分比
        $data['cityHousePriceData']['average_price_percent']=$cityHousePriceData2 && $cityHousePriceData2['average_price']>0?100*$data['cityHousePriceData']['average_price_sub']/$cityHousePriceData2['average_price']:0;
        $data['cityHousePriceData']['average_price_percent']=round($data['cityHousePriceData']['average_price_percent'],2);

        //用本月数据减去上月数据
        $data['cityHousePriceData']['trade_num_sub']=$cityHousePriceData1?$cityHousePriceData1['trade_num']-($cityHousePriceData2?$cityHousePriceData2['trade_num']:0):0;
        // 比上月的百分比
        $data['cityHousePriceData']['trade_num_percent']=$cityHousePriceData2&&$cityHousePriceData2['trade_num']>0?100*$data['cityHousePriceData']['trade_num_sub']/$cityHousePriceData2['trade_num']:0;
        $data['cityHousePriceData']['trade_num_percent']=round($data['cityHousePriceData']['trade_num_percent'],2);
        // 资讯
        $newArticleInfo=\app\common\model\xiluhouse\Article::where('status','normal')->where('classify',3)->orderRaw('id desc')->find();
        $hotArticleInfo=\app\common\model\xiluhouse\Article::where('status','normal')->where('classify',3)->orderRaw('view_num desc,weigh desc,id desc')->find();

        // 买房问问 两条数据
        $questionData=\app\common\model\xiluhouse\QAndA::where('status','normal')->orderRaw('weigh desc,id desc')->limit(2)->select();

        // 动态 两条数据
        $houseTrendsData=\app\common\model\xiluhouse\HouseTrends::with(['house'])->where('house.status','normal')->where('house_trends.status','normal')->orderRaw('weigh desc,id desc')->limit(2)->select();
        // 上下轮播资讯（classify=1），买房问问（classify=2），动态（classify=3）数据 
        $data['informationData']=[];
        $nowArticleData = [];
        if($newArticleInfo||$hotArticleInfo){
            if($newArticleInfo){
                $newArticleInfo['is_new_or_hot']='new';
                $nowArticleData[]=$newArticleInfo;
            }
            if($hotArticleInfo){
                $hotArticleInfo['is_new_or_hot']='hot';
                $nowArticleData[]=$hotArticleInfo;
            }
            $data['informationData'][]=[
                'classify'=>1,
                'classify_text'=>'资讯',
                'data'=>$nowArticleData
            ];
        }
        if(!empty($questionData)){
            foreach ($questionData as $key => $value) {
                $questionData[$key]['name']=$value['question'];
            }
            $data['informationData'][]=[
                'classify'=>2,
                'classify_text'=>'买房问问',
                'data'=>$questionData
            ];
        }
        if(!empty($houseTrendsData)){
            foreach ($houseTrendsData as $key => $value) {
                $houseTrendsData[$key]['name']=$value['house']['name'].$value['name'];
            }
            $data['informationData'][]=[
                'classify'=>3,
                'classify_text'=>'房源动态',
                'data'=>$houseTrendsData
            ];
        }

         
        // 首页推荐热门房源
        $data['hotHouseData']=\app\common\model\xiluhouse\House::where('status','normal')->where('city','like',$city.'%')->order('is_hot desc,collect_num desc,weigh desc,id desc')->limit(5)->select();
        // 首页推荐咨询师
        $data['brokerData']=\app\common\model\xiluhouse\User::field('salt,password,ip,joinip,bio,jointime,level,loginip,loginfailure,token',true)->with('userprofile')->where('userprofile.is_broker',2)->where('status','normal')->where('userprofile.city','like',$city.'%')->orderRaw('satisfaction_degree desc,weigh desc,id desc')->limit(2)->select();

        // 首页当前资讯管理
        $session_list = \app\common\model\xiluhouse\ChatSession::with(['senduser'=>function($query){
            $query->withField(['id','avatar','nickname','username','bio','score','mobile']);
        }])->where('deletetime', null)
            ->order('createtime desc')
            ->limit(5) 
            ->select();
        $data['chat_log_data']=[];
        foreach ($session_list as $key => $value) {
            $mobile_text=substr($value['senduser']['mobile'],7,4);
            $data['chat_log_data'][]=[
                'msg'=>'尾号为'.$mobile_text.'用户正在咨询',
                'createtime_text'=>date('Y-m-d',$value['createtime']),
            ];
        }
        $this->success('',$data);
    }

    /***********二手房源*************/
    /**
     * @title  二手房搜索数据
     * @desc  搜索价格、户型
     */
    public function search_field_data3(){
        //获取搜索价格
        $data['priceData']=\app\common\model\xiluhouse\market\SearchPrice::where('status','normal')->orderRaw('weigh desc,id desc')->select();
        //获取搜索户型
        $data['roomnumData']=\app\common\model\xiluhouse\market\SearchRoomnum::where('status','normal')->orderRaw('weigh desc,id desc')->select();
        //用途
        $data['purposeData'] = \app\common\model\xiluhouse\market\MarketPurpose::field("id,name")->where('status','normal')->orderRaw('weigh desc,id desc')->select();
        //装修
        $data['decorationData'] = \app\common\model\xiluhouse\market\MarketDecoration::field("id,name")->where('status','normal')->orderRaw('weigh desc,id desc')->select();
        $this->success('',$data);
    }
    /**
     * 用途
     */
    public function market_purpose(){
        $purpose = \app\common\model\xiluhouse\market\MarketPurpose::field("id,name")->where('status','normal')->orderRaw('weigh desc,id desc')->select();
        $this->success('',$purpose);
    }
    /**
     * 装修
     */
    public function market_decoration(){
        $decoration = \app\common\model\xiluhouse\market\MarketDecoration::field("id,name")->where('status','normal')->orderRaw('weigh desc,id desc')->select();
        $this->success('',$decoration);
    }
}
